import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import request from "../../server/request";
import styles from './index.module.less'
import { Popover } from "antd";
import LoginBox from "../LoginBox";
//action
import { setUserInfo, setPath } from "./reducer/actions";
import { setToken } from "../LoginBox/Redux/actions";
import { connect } from "react-redux";
import UserInfo from "../UserInfo";
import { useSelector } from "react-redux";
const mapStateToProps = (state: any) => ({
    info: state.userInfo.avatar,
    path: state.headerState.path,
    token: state.loginInfo.token,
    loginInfo: state.loginInfo
});
const mapDispatchToProps = {
    setUserInfo,
    setPath,
    setToken
}

interface User_Info {
    email: string,
    nickName: string,
    avatar: string,
    breif: string | undefined,
    followData: {
        fansCount: number,
        followCount: number
    },
    gender: string
}
interface FCprops {
    setUserInfo: (data: User_Info) => any,
    setPath: (path: string) => any,
    setToken: (token: string | null) => any,
    info: User_Info,
    path: string,
    token: string | null,
    loginInfo: any

}
const Header: React.FC<FCprops> = ({ setUserInfo, info, path, setPath, token, setToken, loginInfo }) => {
    const menu = [
        {
            label: '首页',
            path: '/explore'
        },
        token ? {
            label: '创作',
            path: '/create'
        } : null,
        token ? {
            label: '数据查看',
            path: '/data_viewing'
        } : null,
        {
            label: '个人主页',
            path: `/user_page/${localStorage.getItem('userId')}`
        }
    ].filter(item => item !== null);

    // const [avatar, setAvatar] = useState<string>('');
    const avatar = useSelector((store:any) => {
        return store.userInfo.avatar;
    })
    const history = useHistory();
    const [isLogin, setIsLogin] = useState(Boolean(token));
    const [open, setOpen] = useState(false);


    useEffect(() => {
        const { pathname } = history.location;
        setPath(pathname);
        request('/userInfo', { user_id: localStorage.getItem('userId') }, "get").then((res: any) => {
            const { avatar } = res;
            // setAvatar(avatar);
            setUserInfo(res);
        });

    }, []);

    useEffect(() => {
        console.log(loginInfo);
        setIsLogin(Boolean(loginInfo.token));

    }, [loginInfo])
    const handlePush = (path: string) => {
        history.push(path);
        setPath(path);
    }
    return (
        <header className={styles['header']}>
            <a className={styles['icon']} href="http://localhost:5173/">
                <img src="src/assets/111.png" width="100px" />
            </a>
            <div className={styles['right']}>
                <div className={styles['navbar']}>
                    {
                        menu.map((item) => {
                            return (
                                <div className={styles['nav-item'] + " " + (item!.path == history.location.pathname ? styles['active'] : "")} key={item!.path} onClick={() => handlePush(item!.path)}>
                                    <span>{item!.label}</span>
                                </div>
                            )
                        })
                    }

                </div>
                <div className={styles['user']}>
                    <Popover
                        title={null}
                        content={<DropDown setToken={setToken} setIsLogin={setIsLogin} openChange={(open: boolean) => setOpen(open)} />}
                        trigger='hover'
                        open={open}
                        onOpenChange={(open: boolean) => setOpen(open)}
                    >
                        <img className={styles['avatar']}
                            src={avatar}
                            alt="登录"
                        />
                    </Popover>

                </div>
            </div>
            {
                !loginInfo.token && <LoginBox path={path} isLogin={isLogin} setIsLogin={setIsLogin} />
            }
        </header>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(Header);

interface D {
    setToken: (token: string | null) => any,
    setIsLogin: (isLogin: boolean) => void,
    openChange: (open: boolean) => void
}
const DropDown: React.FC<D> = ({ setToken, setIsLogin, openChange }) => {

    const [open, setOpen] = useState(false);
    const handleExit = () => {
        // 退出登录
        setToken(null);
        localStorage.removeItem('token');
        openChange(false);
    }
    const toLogin = () => {
        setIsLogin(false);
        openChange(false)
    }
    return (
        <div className={styles['drop-down']}>
            {
                localStorage.getItem('token')
                    ?
                    <>
                        <span onClick={() => setOpen(true)}>修改资料</span>
                        <span onClick={handleExit}>退出登录</span>
                    </>
                    : <span onClick={toLogin}>登录</span>
            }
            {
                open && <UserInfo open={open} setOpen={setOpen} />
            }

        </div>
    )
}